/* internal/js/order/maintain.js */

/* Common */

var SERVLET_PATH = '/ordrs/internal/maintain-order'; 

/* END Common */


/* Create */

function createOrder (itemAdded) {
	createOrderValidate(itemAdded);
}

function createOrderValidate (itemAdded) {
	var firstname = document.getElementById('firstname').value;
	var lastname = document.getElementById('lastname').value;
	var phone = document.getElementById('phone').value;
	var status = document.getElementById('orderStatus')
		.options[document.getElementById('orderStatus').selectedIndex].value;
	var paymentStatus = document.getElementById('paymentStatus')
		.options[document.getElementById('paymentStatus').selectedIndex].value;
	var delivery = document.getElementById('orderType').selectedIndex;
	
	var valid = true;

	if (firstname == '') { //left blank
		valid = false;
		showFieldRequired('firstnameMessage');
	}
	else
		hideFieldMessage('firstnameMessage');

	if (phone == '') { //left blank
		valid = false;
		showFieldRequired('phoneMessage');
	}
	else if (!isNumeric(phone)) { // not numeric
		valid = false;
		showFieldMessage('phoneMessage','Must be number');
	}
	else
		hideFieldMessage('phoneMessage');

	if (status == '') { //left blank
		valid = false;
		showFieldRequired('orderStatusMessage');
	}
	else
		hideFieldMessage('orderStatusMessage');
	
	if (paymentStatus == '') {//left blank
		valid = false;
		showFieldRequired('paymentStatusMessage');
	}
	else
		hideFieldMessage('paymentStatusMessage');
	
	if (valid)
		createOrderSend(firstname, lastname, phone, status, paymentStatus, delivery, itemAdded);
}

function createOrderSend (firstname, lastname, phone, status, paymentStatus, delivery, itemAdded) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('c') +
	            '&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
	            '&phone=' + encodeURI(phone) +
	            '&status=' + encodeURI(status) +
	            '&paymentstatus=' + encodeURI(paymentStatus) +
	            '&delivery=' + encodeURI(delivery);
	
	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				createOrderReceive(req.responseXML, itemAdded);
			} else if (req.status == 204) {
				//can't find server
				createOrderReceive(encodeErrorXML('-1', 'Cannot find server.'), false);
			}
		}
	};
	sendPost(req, url, params);
}

function createOrderReceive (xml, itemAdded) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	var orderID = getErrorDetail(xml);
	if (code == 0) {
		if (itemAdded) {
			document.getElementById('orderID').value = orderID;
			addItem();
		}
		else
			reportOrder(orderID);
		showDialog('New Order created.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Create */

/* Report */

function reportOrder(orderID) {
	reportOrderValidate(orderID);
}

//done
function reportOrderValidate (orderID) {
	try {
		orderID.length;
	} catch(e) {
		orderID = '';
	}
	var firstname = document.getElementById('firstname').value;
	var lastname = document.getElementById('lastname').value;
	var phone = document.getElementById('phone').value;
	var status = document.getElementById('orderStatus').options[document.getElementById('orderStatus').selectedIndex].value;
	var paymentStatus = document.getElementById('paymentStatus').options[document.getElementById('paymentStatus').selectedIndex].value;
	
	reportOrderSend(orderID, firstname, lastname, phone, status, paymentStatus);
}

//done
function reportOrderSend (orderID, firstname, lastname, phone, status, paymentStatus) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('r') +
				'&id=' + encodeURI(orderID) +
				'&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
		        '&phone=' + encodeURI(phone) + 
		        '&status=' + encodeURI(status) +
		        '&paymentStatus=' + encodeURI(paymentStatus);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				reportOrderReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				reportOrderReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function reportOrderReceive (xml) {
	if (xml.getElementsByTagName('orders').length > 0) {
		var orders = xml.getElementsByTagName('orders')[0];
		showResults(buildTable(orders));
		if (orders.childNodes.length == 1) {
			var id = orders.childNodes[0].getElementsByTagName('id')[0].childNodes[0].nodeValue;
			showResult(id);
			listOrderItem(id);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10101)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END Report */



/* Update */

function updateOrder() {
	updateOrderValidate();
}

function updateOrderValidate () {
	var id = document.getElementById('orderID').value;
	var firstname = document.getElementById('firstname').value;
	var lastname = document.getElementById('lastname').value;
	var phone = document.getElementById('phone').value;
	var status = document.getElementById('orderStatus').options[document.getElementById('orderStatus').selectedIndex].value;
	var paymentStatus = document.getElementById('paymentStatus').options[document.getElementById('paymentStatus').selectedIndex].value;
	
	
	var valid = true;

	if (firstname == '') { //left blank
		valid = false;
		showFieldRequired('firstnameMessage');
	}
	else
		hideFieldMessage('firstnameMessage');

	if (phone == '') { //left blank
		valid = false;
		showFieldRequired('phoneMessage');
	}
	else if (!isNumeric(phone)) { // not numeric
		valid = false;
		showFieldMessage('phoneMessage','Must be number');
	}
	else
		hideFieldMessage('phoneMessage');

	if (status == '') { //left blank
		valid = false;
		showFieldRequired('orderStatusMessage');
	}
	else
		hideFieldMessage('orderStatusMessage');
	
	if (paymentStatus == '') {//left blank
		valid = false;
		showFieldRequired('paymentStatusMessage');
	}
	else
		hideFieldMessage('paymentStatusMessage');
	
	
	if (valid)
		updateOrderSend(id, firstname, lastname, phone, status, paymentStatus);
}

//really done
function updateOrderSend (id, firstname, lastname, phone, status, paymentStatus) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('u') +
	            '&id=' + encodeURI(id) +
	            '&firstname=' + encodeURI(firstname) +
	            '&lastname=' + encodeURI(lastname) +
	            '&phone=' + encodeURI(phone) +
	            '&status=' + encodeURI(status) +
	            '&paymentstatus=' + encodeURI(paymentStatus);
	
	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				updateOrderReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				updateOrderReceive(encodeErrorXML('-1', 'Cannot find server.'), false);
			}
		}
	};
	sendPost(req, url, params);
}


function updateOrderReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		listAllOrderSend();
		showDialog('Order updated.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Update */


/* Delete */

function deleteOrder() {
	openConfirmModalDialog('Please Confirm',
			'Are you sure you want to delete this order?','deleteOrderValidate');
}

function deleteOrderValidate () {
	var id = document.getElementById('orderID').value;
	if (id == '') {
		//no item selected
		showDialog('No order is selected for deletion.');
	} else {
		//item selected
		deleteOrderSend(id);
	}
}


function deleteOrderSend (id) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('d') +
	            '&id=' + encodeURI(id);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				/* returned code */
				deleteOrderReceive(req.responseXML);
			} else if (req.status == 204) {
				/* can't find server */
				deleteOrderReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function deleteOrderReceive (xml) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		resetFields();
		listAllOrderSend();
		showDialog('Order deleted.');
	} else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Delete */


/* List All */

function listAllOrder () {
	listAllOrderSend();
}

function listAllOrderSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('l');
	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listAllOrderReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listAllOrderReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}


function listAllOrderReceive (xml) {
	if (xml.getElementsByTagName('orders').length > 0) {
		var orders = xml.getElementsByTagName('orders')[0];
		showResults(buildTable(orders));
		if (orders.childNodes.length == 1) {
			var id = orders.childNodes[0].getElementsByTagName('id')[0].childNodes[0].nodeValue;
			showResult(id);
			listOrderItem(id);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10201)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END List All */

/* List Order Status */

function listOrderStatus () {
	listOrderStatusSend();
}

function listOrderStatusSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('s');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listOrderStatusReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listOrderStatusReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}


function listOrderStatusReceive (xml) {
	if (xml.getElementsByTagName('types').length > 0) {
		var types = xml.getElementsByTagName('types')[0];
		for (var loop = 0; loop < types.childNodes.length; loop++) {
			var type = types.childNodes[loop];
			var name = type.getElementsByTagName('name')[0].childNodes[0].nodeValue;
			var optgroup = document.getElementById('orderStatusOptGroup');
			var opt = document.createElement('option');
			opt.setAttribute('value', name);
			opt.innerHTML = name;
			optgroup.appendChild(opt);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10301)
			showDialog(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END List Order Status */

/* List Payment Status */

function listPaymentStatus () {
	listPaymentStatusSend();
}

function listPaymentStatusSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('p');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listPaymentStatusReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listPaymentStatusReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}


function listPaymentStatusReceive (xml) {
	if (xml.getElementsByTagName('types').length > 0) {
		var types = xml.getElementsByTagName('types')[0];
		for (var loop = 0; loop < types.childNodes.length; loop++) {
			var type = types.childNodes[loop];
			var name = type.getElementsByTagName('name')[0].childNodes[0].nodeValue;
			var optgroup = document.getElementById('paymentStatusOptGroup');
			var opt = document.createElement('option');
			opt.setAttribute('value', name);
			opt.innerHTML = name;
			optgroup.appendChild(opt);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10301)
			showDialog(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}


/* END List Payment Status */


/* List Order Item */

function listOrderItem (orderID) {
	listOrderItemSend(orderID);
}


function listOrderItemSend (orderID) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('oi') +
				 '&id=' + encodeURI(orderID);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listOrderItemReceive(req.responseXML, orderID);
			} else if (req.status == 204) {
				//can't find server
				listOrderItemReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}


function listOrderItemReceive (xml, orderID) {
	if (xml.getElementsByTagName('orderitems').length > 0) {
		var orderitems = xml.getElementsByTagName('orderitems')[0];
		document.getElementById('orderItemList').innerHTML = buildOrderItemTable(orderitems, orderID);
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10201)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END List Order Items */


/* List Menu Item */

function listMenuItem () {
	listMenuItemSend();
}


function listMenuItemSend () {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('mi');

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				listMenuItemReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				listMenuItemReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

 
function listMenuItemReceive (xml) {
	if (xml.getElementsByTagName('menuitems').length > 0) {
		var menuitems = xml.getElementsByTagName('menuitems')[0];
		document.getElementById('menuItemList').innerHTML = buildMenuItemTable(menuitems);
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10201)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}

/* END List Menu Items */

/* Add an Item to Order */

function addItem() {
	addItemValidate();
}

function addItemValidate() {
	var menuItemID = document.getElementById('menuItemID').value;
	var orderID = document.getElementById('orderID').value;
	if (orderID == '') {
		//no order selected, create a new order
		createOrder(true);
	} else if (menuItemID == '') {
		showDialog('No item is selected in the menu.');
	} else {
		//item selected
		addItemSend(orderID, menuItemID);
	}
}

function addItemSend (orderID, menuItemID) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('ai') +
				 '&orderid=' + encodeURI(orderID) +
				 '&menuitemid=' + encodeURI(menuItemID);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				addItemReceive(req.responseXML, orderID);
			} else if (req.status == 204) {
				//can't find server
				addItemReceive(encodeErrorXML('-1', 'Cannot find server.'), orderID);
			}
		}
	};
	sendPost(req, url, params);
}


function addItemReceive (xml, orderID) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		reportOrder(orderID);
	}
	else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}

/* END Add an Item to Order */

/* Remove an Item From Order */

function removeItem() {
	removeItemValidate();
}

function removeItemValidate() {
	var menuItemID = document.getElementById('orderItemID').value;
	var orderID = document.getElementById('orderID').value;
	if (orderID == '') {
		//no order selected
		showDialog('No order is selected.');
	} else if (menuItemID == '') {
		showDialog('No item is selected in the order.');
	} else {
		//item selected
		removeItemSend(orderID, menuItemID);
	}
}

function removeItemSend (orderID, menuItemID) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('ri') +
				 '&orderid=' + encodeURI(orderID) +
				 '&menuitemid=' + encodeURI(menuItemID);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				removeItemReceive(req.responseXML, orderID);
			} else if (req.status == 204) {
				//can't find server
				removeItemReceive(encodeErrorXML('-1', 'Cannot find server.'), orderID);
			}
		}
	};
	sendPost(req, url, params);
}


function removeItemReceive (xml, orderID) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		reportOrder(orderID);
	}
	else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}


/* END Remove an Item From Order */


/* Decrease the quantity of Order Item */

function decreaseItemQty() {
	decreaseItemQtyValidate();
}

function decreaseItemQtyValidate() {
	var menuItemID = document.getElementById('orderItemID').value;
	var orderID = document.getElementById('orderID').value;
	if (orderID == '') {
		//no order selected
		showDialog('No order is selected.');
	} else if (menuItemID == '') {
		showDialog('No item is selected in the order.');
	} else {
		//item selected
		decreaseItemQtySend(orderID, menuItemID);
	}
}

function decreaseItemQtySend (orderID, menuItemID) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('dq') +
				 '&orderid=' + encodeURI(orderID) +
				 '&menuitemid=' + encodeURI(menuItemID);

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				decreaseItemQtyReceive(req.responseXML, orderID);
			} else if (req.status == 204) {
				//can't find server
				decreaseItemQtyReceive(encodeErrorXML('-1', 'Cannot find server.'), orderID);
			}
		}
	};
	sendPost(req, url, params);
}


function decreaseItemQtyReceive (xml, orderID) {
	var code = getErrorCode(xml);
	var message = getErrorMessage(xml);
	if (code == 0) {
		reportOrder(orderID);
	}
	else if (code == -1)
		showDialog(message);
	else
		showDialog('Error ' + getErrorString(xml));
}




/* END Decrease the quantity of Order Item */

/* Search for a Menu Item */

function searchMenuItem() {
	searchMenuItemValidate();
}

//done
function searchMenuItemValidate (name) {
	var itemNo = document.getElementById('itemNumber').value;
	var name = document.getElementById('itemName').value;
	
	if (itemNo != '' && !isNumeric(itemNo)) // not blank and not numeric
		showFieldMessage('itemNumberMessage','Must be number');
	else {
		hideFieldMessage('itemNumberMessage');
		searchMenuItemSend(itemNo, name);
	}
}

//done
function searchMenuItemSend (itemNo, name) {
	var url = SERVLET_PATH;
	var params = 'a=' + encodeURI('si') +
	 			'&number=' + encodeURI(itemNo) +
				'&name=' + encodeURI(name);
	           
		 

	var req = getXmlHttpObject();
	req.onreadystatechange = function() {
		if (req.readyState == 4) {
			if (req.status == 200) {
				//returned code
				searchMenuItemReceive(req.responseXML);
			} else if (req.status == 204) {
				//can't find server
				searchMenuItemReceive(encodeErrorXML('-1', 'Cannot find server.'));
			}
		}
	};
	sendPost(req, url, params);
}

function searchMenuItemReceive (xml) {
	if (xml.getElementsByTagName('menuitems').length > 0) {
		var menuItems = xml.getElementsByTagName('menuitems')[0];
		document.getElementById('menuItemList').innerHTML = buildMenuItemTable(menuItems);
		if (menuItems.childNodes.length == 1) {
			var id = menuItems.childNodes[0].getElementsByTagName('id')[0].childNodes[0].nodeValue;
			selectMenuItemRow(id);
		}
	} else {
		var code = getErrorCode(xml);
		var message = getErrorMessage(xml);
		if (code == 10101)
			showResults(message);
		else if (code == -1)
			showDialog(message);
		else
			showDialog('Error ' + getErrorString(xml));
	}
}



/* END Search for a Menu Item */

/* Format check */

function isNumeric(strToCheck) {
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;

	if (strToCheck.length == 0) 
		return false;

	//  test strString consists of valid characters listed above
	for (var i = 0; i < strToCheck.length && blnResult; i++) {
	strChar = strToCheck.charAt(i);
   	if (strValidChars.indexOf(strChar) == -1)
	   blnResult = false;
	}
	return blnResult;
}

/* END Format check */